# -*- coding: utf-8 -*-
import sys
import os
import tempfile
import requests
# import mic
import signal
import threading
import time
from mic import Audio
import wave
import base64
import pyaudio
import urllib
# import urllib
from uuid import getnode as get_mac
from gstreamer_player import Player
# import pyaudio
class record(object):
    def __init__(self):
        self.framedate=[]
    def put(self,data):
        print u"收到"
        self.framedate.append(data)


def getVoice( text, filename):
    # 2. 向Rest接口提交数据
    getvoice_url = "http://tsn.baidu.com/text2audio?tex=%s&lan=zh&cuid=%s&ctp=1&tok=%s"
    get_url = getvoice_url % (urllib.quote(text), str(get_mac())[:32], "24.fda875d391a9763ab8e45e104fc76cb8.2592000.1549010343.282335-15107613")

    voice_data = urllib.urlopen(get_url).read()

    # 3.处理返回数据
    voice_fp = open(filename, 'wb+')
    voice_fp.write(voice_data)
    voice_fp.close()
    pass


if __name__ == '__main__':


    def get_speech( phrase):

        query = {'tex': phrase,
                 'lan': 'zh',
                 'tok': "24.fda875d391a9763ab8e45e104fc76cb8.2592000.1549010343.282335-15107613",
                 'ctp': 1,
                 'cuid': str(get_mac())[:32],
                 'per': "0"
                 }
        r = requests.post('http://tsn.baidu.com/text2audio',
                          data=query,
                          headers={'content-type': 'application/json'})
        print (u"开始百度tts %s" % query)
        try:
            r.raise_for_status()

            # print(u"结果")
            # print(u"结果百度tts  %s" % r.json())
            if r.json()['err_msg'] is not None:

                return None
        except Exception:
            # traceback.print_exc()
            # print(u"开始百度tts 失败 %s" % traceback.print_exc())
            # return None
            pass
        # self._logger.info(u"百度tts返回内容 %s",r.content)
        # print ("base 64  %s  " % base64.b64encode(r.content))

        filename = "123"
        # with open(os.path.join("/home/respeaker/git/respeaker_demo/mic/", '{}.mp3'.format(filename)), 'wb') as f:
        #
        #     f.write(r.content)

        wav_fp = wave.open(r"/home/respeaker/git/respeaker_demo/mic/11000.mp3", 'wb')
        wav_fp.setnchannels(1)
        wav_fp.setsampwidth(pyaudio.get_sample_size(pyaudio.paInt16))
        wav_fp.setframerate(16000)
        wav_fp.writeframes(''.join(r.content))
        wav_fp.close()
        head = r.headers
        print head
        # with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as f:
        #     f.write(r.content)
        #     tmpfile = f.name
        #     print f.name


    # return tmpfile

    mp3_file = "/home/respeaker/git/respeaker_demo/mic/222244.mp3"
    getVoice("我在想你啊",mp3_file)
    # os.system("paplay /home/respeaker/git/respeaker_demo/mic/out1.mp3")
    # get_speech("你好啊")

        # with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as f:
        #     f.write(r.content)
        #     tmpfile = f.name
        #     return tmpfile

    # rc=record()

    # tempmic=Audio()
    # tempmic.link(rc)
    #
    player=Player()

    player.play('file://{}'.format(mp3_file))

    is_quit = threading.Event()
    #
    #
    def signal_handler(signal, frame):
        print('Quit')
        is_quit.set()
    #
    #
    signal.signal(signal.SIGINT, signal_handler)

    # tempmic.start()
    while not is_quit.is_set():
        try:
            time.sleep(1)
        except SyntaxError:
            pass
        except NameError:
            pass

    # RATE = 16000
    # with tempfile.SpooledTemporaryFile(mode='w+b') as f:
    #     wav_fp = wave.open(r"/home/respeaker/git/respeaker_demo/mic/123.mp3", 'wb')
    #     wav_fp.setnchannels(1)
    #     wav_fp.setsampwidth(pyaudio.get_sample_size(pyaudio.paInt16))
    #     wav_fp.setframerate(RATE)
    #     wav_fp.writeframes(''.join(rc.framedate))
    #     wav_fp.close()
    #     f.seek(0)
    #     print ("%s"% f.name)
    # frames = []
    #
    print ("exit")




